const express = require("express");
const cors = require("cors");
const fs = require("fs");
const path = require("path");
const { formidable } = require("formidable");
const app = express();
// 跨域中间件
app.use(cors());
// 处理formdata数据格式中间件
app.post("/registry", (req, res) => {
  const form = formidable({
    keepExtensions: true,
    uploadDir: path.join(__dirname, "./img"),
  });

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    //需求更改名字，让文件可以正常打开
    const oldPath = files.file[0].filepath;
    const newPath = path.join(
      __dirname,
      "./img",
      files.file[0].originalFilename
    );
    fs.renameSync(oldPath, newPath, (err) =>{ 
      if(err) {
        return;
      }
      console.log('rename')
    })
    res.json({ fields, files });
  });
});

app.listen(3000, () => {
  console.log("Example app listening on port 3000!");
});
